import {Button, message, Popconfirm} from 'antd';
import {ModalForm} from "@ant-design/pro-form";
import {ProList} from "@ant-design/pro-list"
import {useEffect, useState} from "react";
import {addFamily, deleteFamily, queryFamily, updateFamily} from "@/pages/User/Account/settings/components/service";
import {DeleteOutlined} from "@ant-design/icons";
import {ProFormText} from "@ant-design/pro-form";

/**
 * 删除节点
 *
 * @param record
 */
const handleSingleRemove = async (record: any) => {
  const hide = message.loading('正在删除');
  try {
    const res = await deleteFamily({
      key: record.id,
    });
    hide();
    if (res) {
      if (res.status === 'done') {
        message.success(res.message);
        return true;
      } else {
        message.error(res.message);
        return false;
      }
    } else {
      message.error('请求超时，请稍后重试');
      return false;
    }
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};

/**
 * 添加节点
 *
 * @param fields
 */

const handleAdd = async (fields: any) => {
  const hide = message.loading('正在添加...');

  try {
    const res = await addFamily({ ...fields });
    if (res && res.status === 'done') {
      hide();
      message.success(res.message);
      return true;
    } else {
      hide();
      message.error(res.message);
      return false;
    }
  } catch (error) {
    hide();
    message.error('添加失败请重试！');
    return false;
  }
};

export default () => {
  const [dataSource, setDatasource] = useState<any[]>([])
  const [update, setUpdate] = useState<boolean>(true)
  const [createModalVisible, handleModalVisible] = useState<boolean>(false);

  // 从后台获取数据
  useEffect(() => {
    queryFamily().then((res)=>{
      if (res.status === "done"){
        // 数据获取成功
        // 整理list为prolist对象
        const data = [...dataSource];

        // 先清空
        data.splice(0, data.length)

        // 填充新数据
        // eslint-disable-next-line array-callback-return
        res.data?.map((item: string)=>{
          data.push({
            name: item,
            id: item,
          })
        })
        setDatasource(data)
        console.log("update", res)
        console.log("update", dataSource)
      }
    })
  }, [update]);

  return (
    <>
    <ProList<any>
      toolBarRender={() => {
        return [
          <Button key="add" type="primary" onClick={()=>{handleModalVisible(true)}}>
            新增
          </Button>,
        ];
      }}
      rowKey="name"
      headerTitle="成员列表"
      dataSource={dataSource}
      editable={{
        type: 'multiple',
        actionRender: (row, config, defaultDoms) => {
          return [defaultDoms.save, defaultDoms.cancel];
        },
        onSave: async (key, record) => {
          try {
            const res = await updateFamily(key, record);
            if (res && res.status === "done"){
              // 修改成功
              message.success(res.message)
              if (update){
                setUpdate(false)
              }else {
                setUpdate(true)
              }
              return true
            }else {
              message.error(res.message)
              return false
            }
          }catch (error){
            message.error("修改保存失败，请稍后重试！" + error)
            return false
          }
        },
      }}
      metas={{
        title: {
          dataIndex: 'name',
        },
        actions: {
          render: (text: any, row: { name: string }, _,action) => [
            <a
              key="edit"
              onClick={()=>{
                action?.startEditable(row.name);
              }}
            >
              修改
            </a>,
            <Popconfirm key="popconfirm" title={`确认删除吗?`} okText="是" cancelText="否" onConfirm={async () => {
              const success = await handleSingleRemove(row);
              if (success) {
                if (update){
                  setUpdate(false)
                }else {
                  setUpdate(true)
                }
              }
            }}>
              <a style={{color: "red"}} ><DeleteOutlined /> 删除</a>
            </Popconfirm>
          ],
        },
      }}
    />
      <ModalForm
        title="新增消费成员"
        width="600px" // 注销可由其自动管理宽度
        visible={createModalVisible}
        onVisibleChange={handleModalVisible}
        onFinish={async (value) => {
          const success = await handleAdd(value);
          if (success) {
            handleModalVisible(false);
            if (update){
              setUpdate(false)
            }else {
              setUpdate(true)
            }
          }
        }}
      >
        <ProFormText
          name={"name"}
          rules={[{required: true, message: "必填！"}]}
        />
      </ModalForm>
    </>
  );
};
